package com.business.commons.date;

import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

/**
 * @author Administrator
 * 
 *         更改所生成类型注释的模板为 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public class TimeUtil {

	private TimeUtil() {
	}

	static {
		String s = "121";
		s.charAt(0);

	}

	private static TimeUtil instance;

	public static TimeUtil get() {
		if (instance == null) {
			instance = new TimeUtil();
		}
		return instance;
	}

	/*
	 * 获取当前时间
	 */
	public String getTime() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String sj_str = dateFormat.format(new Date());

		return sj_str;
	}

	/**
	 * 指定Date 格式化
	 * 
	 * @param date
	 * @param patten
	 * @return
	 * @Date:2014-3-20下午2:08:56
	 */
	public String getTime(Date date, String patten) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(patten);
		String sj_str = dateFormat.format(date);

		return sj_str;
	}

	/**
	 * 返回二个时间之间相差的秒数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 * @throws ParseException
	 */
	public Long getSkip(String beginDate, String endDate) throws ParseException {
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date begin = dfs.parse(beginDate);
		java.util.Date end = dfs.parse(endDate);
		long between = (end.getTime() - begin.getTime()) / 1000;// 除以1000是为了转换成秒
		return between;
	}

	/*
	 * 获取当前日期
	 */
	public String getDate() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String sj_str = dateFormat.format(new Date());

		return sj_str;
	}

	/*
	 * 获取当前日期
	 */
	public String getDate(String formatstr) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(formatstr);
		String sj_str = dateFormat.format(new Date());

		return sj_str;
	}

	/*
	 * 格式化时间
	 */
	public String formatTime(Date date) {

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String sj_str = dateFormat.format(date);

		return sj_str;
	}

	/*
	 * 格式化日期
	 */
	public String formatDate(Date date) {
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		
		return  dateFormat.format(date);
	}

	/*
	 * 格式化日期
	 */
	public String formatDate(Date date,String pattern) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

		return dateFormat.format(date);
	}

	/*
	 * 解析日期字符串
	 */
	public Date parseDate(String dateStr) {

		return parseDate("yyyy-MM-dd", dateStr);
	}

	/*
	 * 解析日期字符串
	 */
	public Date parseDate(String pattern, String dateStr) {
		if (null == dateStr) {
			return null;
		}
		Date date = null;

		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

		try {
			date = dateFormat.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return date;
	}

	/*
	 * 解析时间字符串
	 */
	public Date parseTime(String timeStr) {
		if (null == timeStr) {
			return null;
		}

		Date date = null;

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		try {
			date = dateFormat.parse(timeStr);
		} catch (ParseException e) {
		}

		return date;
	}

	/*
	 * 时间偏移运算
	 */
	public String getTime(int skipDay) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(new Date());

		cal.add(GregorianCalendar.DAY_OF_MONTH, skipDay);
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		return dateFormat.format(cal.getTime());
	}

	/*
	 * 某一时间的偏移运算
	 */
	public String getTime(String timeStr, int skipDay) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(parseTime(timeStr));

		cal.add(GregorianCalendar.DAY_OF_MONTH, skipDay);
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		return dateFormat.format(cal.getTime());
	}

	/*
	 * 日期偏移运算(增、减几日）
	 */
	public String getDate(int skipDay) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(new Date());

		cal.add(GregorianCalendar.DAY_OF_MONTH, skipDay);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

		return dateFormat.format(cal.getTime());
	}

	/*
	 * 日期偏移运算(增、减几日）
	 */
	public String getDate(String dateStr, int skipDay) {
		if (null == dateStr) {
			return null;
		}

		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(parseDate(dateStr));

		cal.add(GregorianCalendar.DAY_OF_MONTH, skipDay);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

		return dateFormat.format(cal.getTime());
	}

	/*
	 * 时间偏移运算(增、减几日、几小时、几分）
	 */
	public String getTime(int skipDay, int skipHour, int skipMinute) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(new Date());

		cal.add(GregorianCalendar.DAY_OF_MONTH, skipDay);
		cal.add(GregorianCalendar.HOUR_OF_DAY, skipHour);
		cal.add(GregorianCalendar.MINUTE, skipMinute);

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		return dateFormat.format(cal.getTime());
	}

	/*
	 * 某一时间的偏移运算(增、减几日、几小时、几分）
	 */
	public String getTime(String timeStr, int skipDay, int skipHour,
			int skipMinute) {
		if (null == timeStr) {
			return null;
		}

		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(parseTime(timeStr));

		cal.add(GregorianCalendar.DAY_OF_MONTH, skipDay);
		cal.add(GregorianCalendar.HOUR_OF_DAY, skipHour);
		cal.add(GregorianCalendar.MINUTE, skipMinute);
		cal.get(GregorianCalendar.DAY_OF_WEEK_IN_MONTH);

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		return dateFormat.format(cal.getTime());
	}

	/*
	 * 计算日期相差几天
	 */
	public long subtraction(Date minuend, Date subtrahend) {

		long daterange = minuend.getTime() - subtrahend.getTime();
		long time = 1000 * 3600 * 24;

		return (daterange % time == 0) ? (daterange / time)
				: (daterange / time + 1);
	}

	public long getM(Date date) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		return cal.get(GregorianCalendar.DAY_OF_WEEK);
	}

	public String getLastDate(String temp) { // 变量temp是看几天前的天数
		if (temp == null || temp.equals("")) {
			temp = "1";
		}
		int i = Integer.parseInt(temp);
		DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
		Calendar grc = Calendar.getInstance();
		grc.add(GregorianCalendar.DATE, -i);
		return dateFormat.format(grc.getTime());
	}

	// 获取上一年的日期（用来设置查询日期条件）
	public String getLastYearDate() { // 上一年

		Calendar c = Calendar.getInstance();
		int y = c.get(Calendar.YEAR);
		String year = String.valueOf(y - 1);
		return year;
	}

	// 获取上个月的日期（用来设置查询日期条件）
	public String getLastMonthDate() { // 上一月
		Calendar c = Calendar.getInstance();
		int y = c.get(Calendar.YEAR);
		int m = c.get(Calendar.MONTH) + 1;
		String month = null;
		String year = String.valueOf(y);
		if (m > 1) {
			if (m > 10) {
				month = String.valueOf(m - 1);
			} else {
				month = "0" + String.valueOf(m - 1);
			}
		} else {
			year = String.valueOf(y - 1);
			month = String.valueOf(12);
		}

		return year + "-" + month;
	}

	// 获取前一天的日期（用来设置查询日期条件）
	public String getLastDayDate() { // 前一天
		Calendar c = Calendar.getInstance();
		int y = c.get(Calendar.YEAR);
		int m = c.get(Calendar.MONTH) + 1;
		int d = c.get(Calendar.DAY_OF_MONTH);
		int days = 0;
		if (m > 1) {
			days = getMonthsDays(m - 1, y);
		} else {
			days = 31;
		}
		String day = null;
		String month = null;
		String year = String.valueOf(y);
		if (d > 1) { // 大于1号
			day = String.valueOf(d - 1);
			if (m > 9) {
				month = String.valueOf(m);
			} else {
				month = "0" + String.valueOf(m);
			}
		} else if ((d < 2) && (m < 2)) { // 一月一号
			day = String.valueOf(31);
			month = String.valueOf(12);
			year = String.valueOf(y - 1);
		} else if ((d < 2) && (m > 2)) {
			day = String.valueOf(days);
			if (m > 10) {
				month = String.valueOf(m - 1);
			} else {
				month = "0" + String.valueOf(m - 1);
			}
		}

		return year + "-" + month + "-" + day;
	}

	// 判断是否闰年
	public boolean isLeapYear(int year) {
		if ((((year % 4) == 0) && ((year % 100) != 0)) || ((year % 4) == 0)
				&& ((year % 400) == 0)) {
			return true;
		} else {
			return false;
		}
	}

	// 获取每个月的天数
	public int getMonthsDays(int month, int year) {
		if ((isLeapYear(year) == true) && (month == 2)) {
			return 29;
		} else if ((isLeapYear(year) == false) && (month == 2)) {
			return 28;
		}

		if ((month == 1) || (month == 3) || (month == 5) || (month == 7)
				|| (month == 8) || (month == 10) || (month == 12)) {
			return 31;
		}
		return 30;
	}

	public String getWeekDay() {
		DateFormatSymbols symboles = new DateFormatSymbols(Locale.getDefault());
		symboles.setShortWeekdays(new String[] { "", "7", "1", "2", "3", "4",
				"5", "6" });
		SimpleDateFormat date = new SimpleDateFormat("E", symboles);
		return date.format(new Date());
	}

	// 获取年
	public int getYear() {
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.YEAR);
	}

	// 获取月
	public int getMonth() {
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.MONTH);
	}

	// 获取日
	public int getDay() {
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.DAY_OF_MONTH);
	}

	public String getLastMonthDay(int lastmonths) {
		int month = getMonth() + 1;
		if (month - lastmonths > 0) {
			return String.valueOf(getYear()) + "-"
					+ String.valueOf(month - lastmonths) + "-1";
		} else {
			return String.valueOf(getYear() - 1) + "-"
					+ String.valueOf(12 + month - lastmonths) + "-1";
		}
	}

	/**
	 * 判断时间是否重叠交叉
	 * 
	 * @param fromDate1
	 *            时间段一（开始时间）
	 * @param toDate1
	 *            时间段一（结束时间）
	 * @param fromDate2
	 *            时间段二（开始时间）
	 * @param toDate2
	 *            时间段二（结束时间）
	 * @return 时间存在交叉重叠则返回true，否则返回false.
	 */
	public boolean isDateCross(Date fromDate1, Date toDate1, Date fromDate2,
			Date toDate2) {
		if (subtraction(toDate1, fromDate1) >= 0
				&& subtraction(fromDate1, toDate2) > 0) {
			return false;
		}
		if (subtraction(toDate1, fromDate1) >= 0
				&& subtraction(fromDate2, toDate1) > 0) {
			return false;
		}
		return true;
	}

	/**
	 * 获取上周日
	 * 
	 * @param date
	 * @return
	 * @Date:2014-12-8下午5:28:02
	 */
	public Date getLastWeekSunday(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		Calendar cal = Calendar.getInstance();
		cal.setTime(c.getTime());
		cal.add(Calendar.WEEK_OF_YEAR, -1);// 一周
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		return cal.getTime();
	}
	/**获得上周六
	 * @param date
	 * @return 
	 * @Date:2014-12-25上午9:54:52
	 */
	public Date getLastWeekSaturday(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		Calendar cal = Calendar.getInstance();
		cal.setTime(c.getTime());
		cal.add(Calendar.WEEK_OF_YEAR, -1);// 一周
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
		return cal.getTime();
	}


	/**
	 * 根据指定的日期获得上个月第一天的日期
	 * 
	 * @param date
	 * @return
	 * @Date:2014-12-1上午11:03:57
	 */
	public Date getPreviousMonthFirst(Date date) {
		Calendar lastDate = Calendar.getInstance();
		lastDate.setTime(date);
		lastDate.set(Calendar.DATE, 1);// 设为当前月的1号
		lastDate.add(Calendar.MONTH, -1);// 减一个月，变为下月的1号
		// lastDate.add(Calendar.DATE,-1);//减去一天，变为当月最后一天
		return lastDate.getTime();
	}

	/**
	 * 获得上个月最后一天的日期
	 * 
	 * @param date
	 * @return
	 * @Date:2014-12-1上午11:05:51
	 */
	public Date getPreviousMonthEnd(Date date) {
		Calendar lastDate = Calendar.getInstance();
		lastDate.setTime(date);
		lastDate.add(Calendar.MONTH, -1);// 减一个月
		lastDate.set(Calendar.DATE, 1);// 把日期设置为当月第一天
		lastDate.roll(Calendar.DATE, -1);// 日期回滚一天，也就是本月最后一天
		return lastDate.getTime();
	}

	/**
	 * 获取上一年的第一天
	 * 
	 * @param date
	 * @return
	 * @Date:2014-12-1上午11:15:51
	 */
	public Date getPreviousYearFirst(Date date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");// 可以方便地修改日期格式
		String years = dateFormat.format(date);
		int years_value = Integer.parseInt(years);
		years_value--;
		return this.parseDate("yyyy-MM-dd", years_value + "-01-01");
	}

	/**
	 * 获取上一年最后一天
	 * 
	 * @param date
	 * @return
	 * @Date:2014-12-1上午11:17:38
	 */
	public Date getPreviousYearLast(Date date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");// 可以方便地修改日期格式
		String years = dateFormat.format(date);
		int years_value = Integer.parseInt(years);
		years_value--;
		return this.parseDate("yyyy-MM-dd", years_value + "-12-31");
	}

	/**获取二个日期间相差天数
	 * @param beginDate
	 * @param endDate
	 * @return 
	 * @Date:2014-12-12下午1:00:33
	 */
	public Integer getDays(Date beginDate,Date endDate){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	    long to = 0;
	    long from = 0;
		try {
			to = df.parse(getTime(endDate,"yyyy-MM-dd")).getTime();
			from = df.parse(getTime(beginDate,"yyyy-MM-dd")).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
		return (int) ((to - from) / (1000 * 60 * 60 * 24));
	}
	
	
	
	
	
	/**
     * 判断当前日期是星期几
     * 
     * @param pTime 修要判断的时间
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
	 public  int dayForWeek(Date pTime)  {
	  Calendar c = Calendar.getInstance();
	  c.setTime(pTime);
	  int dayForWeek = 0;
	  if(c.get(Calendar.DAY_OF_WEEK) == 1){
	   dayForWeek = 7;
	  }else{
	   dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
	  }
	  return dayForWeek;
	 }
	 
	 /**
	     * 判断当前日期是星期几
	     * 
	     * @param pTime 修要判断的时间
	     * @return dayForWeek 判断结果
	     * @Exception 发生异常
	     */
		 public  int dayForWeek(String pTime)  {
		  Calendar c = Calendar.getInstance();
		  c.setTime(parseDate("yyyy-MM-dd", pTime));
		  int dayForWeek = 0;
		  if(c.get(Calendar.DAY_OF_WEEK) == 1){
		   dayForWeek = 7;
		  }else{
		   dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
		  }
		  return dayForWeek;
		 }
		 
		
		 /**
		  * 得到对应月份的天数
		  */
			public int getDays(int year,int month ){
				switch (month) {
				case 1:
				case 3:
				case 5:
				case 7:
				case 8:
				case 10:
				case 12:
					return 31;
				case 4:
				case 6:
				case 9:
				case 11:
					return 30;
				case 2:
					if((year%4==0&&year%100!=0)||year%400==0){
						return 29;
					}
					return 28;
				}
				
				throw new IllegalArgumentException("参数有误："+year+","+month);
			}	
			
			
			
		 
	 
	public static void main(String[] args) {
		System.out.println(TimeUtil.get().getLastWeekSunday(new Date()));
		System.out.println(TimeUtil.get().getLastWeekSaturday(new Date()));
		System.out.println(TimeUtil.get().getDays(2008,2));
		
	}
}
